package yoshop_ast

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	"gitee.com/libs_2/yoshop_ast/model"
)

// CreateCategory 创建商品分类
func (c *Client) CreateCategory(ctx context.Context, req *model.SaveCategoryReq) error {
	reqBody, _ := json.Marshal(req)

	body, err := c.doPost(ctx, "/index.php?s=/store/category/add", bytes.NewReader(reqBody))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}

// EditCategory 编辑商品分类
func (c *Client) EditCategory(ctx context.Context, req *model.SaveCategoryReq) error {
	reqBody, _ := json.Marshal(req)

	body, err := c.doPost(ctx, "/index.php?s=/store/category/edit", bytes.NewReader(reqBody))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}

// GetCategoryList 获取商品分类列表
func (c *Client) GetCategoryList(ctx context.Context) ([]model.CategoryItem, error) {
	body, err := c.doGet(ctx, "/index.php?s=/store/category/list")
	if err != nil {
		return nil, err
	}

	var res model.GetCategoryListResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return nil, err
	}

	if res.Status != 200 {
		return nil, errors.New(res.Msg)
	}

	return res.Data.List, nil
}

func (c *Client) DeleteCategory(ctx context.Context, categoryId int64) error {
	body, err := c.doPost(ctx, "/index.php?s=/store/category/delete", strings.NewReader(fmt.Sprintf(`{"categoryId": %d}`, categoryId)))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}
